<!-- LTV -->
<template>
  <div>
    <el-card>
      <div class="topInquire">
        <div>
          <!-- 渠道 -->
          <Channel @channel-event="handleSelectChannel"></Channel>
        </div>

        <div>
        <!-- 服务器 -->
        <Server @server-event="handleSelectServer"></Server>
        </div>

        <div>
        <!-- 日期 -->
        <DatePicker @dateChange="handleDateChange"></DatePicker>
        </div>

        <el-button 
        size="small" 
        icon="el-icon-search" 
        type="primary" @click="handleSearch">搜索</el-button>

        <el-button icon="el-icon-upload2" type="success" 
          size="small" @click="handleExport">导出Excel</el-button>

        <el-button icon="el-icon-refresh" type="success"
        size="small" @click="handleRefresh">刷新实时数据</el-button>
      </div>

      <div>
        <el-table
          ref="table"
          border
          :data="playerLtvData"
          :height="tableHeight"
          show-summary
        >
          <el-table-column prop="bornDate" label="日期" min-width="120" />
          <el-table-column prop="channelInfo" label="渠道信息" min-width="120" />
          <el-table-column  label="整体汇总" align="center">
            <el-table-column prop="playerCount" label="新增角色" min-width="120" />
            <el-table-column prop="rechargeTotal" label="充值金额" min-width="120" />
            <el-table-column prop="payPlayerCount" label="付费人数" min-width="120" />
            <el-table-column prop="payRate" label="付费率" min-width="120" />
          </el-table-column>
          <el-table-column  label="LTV统计" align="center">
            <el-table-column prop="day0" label="LTV-1" min-width="150" />
            <el-table-column prop="day1" label="LTV-2" min-width="150" />
            <el-table-column prop="day2" label="LTV-3" min-width="150" />
            <el-table-column prop="day3" label="LTV-4" min-width="150" />
            <el-table-column prop="day4" label="LTV-5" min-width="150" />
            <el-table-column prop="day5" label="LTV-6" min-width="150" />
            <el-table-column prop="day6" label="LTV-7" min-width="150" />
          </el-table-column>
        </el-table>
      </div>
    </el-card>

  </div>
</template>

<script>
import Channel from '@/components/selectChannel/index.vue'
import Server from '@/components/selectServer/index.vue'
import DatePicker from '@/components/datePicker/index.vue'
import { playerLtv, manualTodayLTV } from '@/api/gameStatistics'

import { export_json_to_excel } from '@/widget/Export2Excel'

export default {
  components: {
   Channel,Server,DatePicker
  },
  data() {
    return {
      playerLtvData: [],
      currentPage: 1, // 当前页
      pageSize: 200, // 每页显示条数
      tableHeight: 0, // 表格高度
      selectChannel:[],
      selectServer:[],
      date:[],
      total:0,
      command:'',
    }
  },

  created() {
    this.getPlayerLtv()
  },

  mounted() {
    this.$nextTick(() => {
      this.getTableHeight()
    })
    window.addEventListener('resize', this.$debounce(this.getTableHeight, 100))
  },

  beforeDestroy() {
    window.removeEventListener('resize', this.getTableHeight)
  },

  methods: {
    // 获取数据
    async getPlayerLtv() {
      const res = await playerLtv({
        page: this.currentPage,
        limit: this.pageSize
      })
      this.playerLtvData = res.data.data.data
      this.total = res.data.data.count
    },

    // 选择日期
    handleDateChange(dateRange){
      this.date = dateRange
    },

    // 选中的渠道
    handleSelectChannel(value){
      this.selectChannel = value
    },

    // 选中的服务器
    handleSelectServer(value){
      this.selectServer = value
    },


    // 搜索
    async handleSearch() {
      try {
        const query = {}
        if (this.date && this.date.length === 2) {
          // 时间戳毫秒转化为秒
          query.startTime = this.$moment(this.date[0]).unix()
          query.endTime = this.$moment(this.date[1]).unix()
        }
        if (this.selectChannel.length !== 0) {
          query.channels = this.selectChannel
        }
        if (this.selectServer.length !== 0) {
          query.serverUids = this.selectServer
        }
        const result = await playerLtv(query)
        this.playerLtvData = result.data.data.data
      } catch (error) {
        console.error(error)
        this.$message.error('发生错误，请稍后重试')
      }
    },

    // 刷新实时数据
    async handleRefresh(){
      const res = await manualTodayLTV()
        if (res.data.code === 0) {
          this.$message.success(res.data.message)
        }
      this.getPlayerLtv()
    },

    // 表格自适应高度
    getTableHeight() {
      if (this.$refs.table && this.$refs.table.$el) {
        this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 140
      } else {
        this.tableHeight = 300
      }
    },

    // 导出
     async handleExport() {
      try {
        const res = await playerLtv({
          limit: this.total
        })

        const newData = res.data.data.data.map(item => {
          const arr = []
          const obj = {
            bornDate: '日期',
            channelInfo: '渠道信息',
            playerCount: '新增角色',
            rechargeTotal: '充值金额',
            payPlayerCount: '付费人数',
            payRate: '付费率',
            day0: 'LTV-1',
            day1: 'LTV-2',
            day2: 'LTV-3',
            day3: 'LTV-4',
            day4: 'LTV-5',
            day5: 'LTV-6',
            day6: 'LTV-7',
          }
          for (const key in obj) {
            arr.push(item[key])
          }
          return arr
        })

        const tHeader = [
          '日期', '渠道信息', '新增角色','充值金额', '付费人数', '付费率', 'LTV-1',
          'LTV-2', 'LTV-3','LTV-4', 'LTV-5', 'LTV-6','LTV-7']

        export_json_to_excel({
          header: tHeader,
          data: newData,
          filename: `LTV（角色）表${this.$moment(new Date()).format('YYYYMMDDHHmm')}`,
          autoWidth: true,
          bookType: 'xlsx'
        })
      } catch (error) {
        this.$message.error(error)
      }
    },
  }
}
</script>
<style lang="scss" scoped>

.topInquire{
  font-weight: bold;
  font-size: 14px;
  color: #6a7488;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
}

</style>
